package com.otdemo.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.otdemo.dao.RestUserDao;
import com.otdemo.entity.RestUser;
import com.otdemo.resp.ResultResponse;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Objects;

@WebServlet("/teacher/add")
public class TeacherAddController extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		req.getRequestDispatcher("/TeacherAdd.jsp").forward(req, resp);
    }

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		BufferedReader reader = req.getReader();
		String s = reader.readLine();
		RestUser rest = new ObjectMapper().readValue(s, RestUser.class);
		RestUser user1 = new RestUserDao().findByUserName(rest.getUsername());
		if (Objects.nonNull(user1)) {
			resp.getWriter().write("<script>alert('账号已存在');</script>");
		}
		new RestUserDao().insert(rest);
		ResultResponse resultResponse = new ResultResponse();
		resp.getWriter().write(new ObjectMapper().writeValueAsString(resultResponse.success()));
	}
}
